package com.example.weather_app.position;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.weather_app.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class SearchCityActivity extends AppCompatActivity {
    private EditText etSearchCity;
    private RecyclerView rvCityList;
    private List<String> originalCityList; // 原始城市列表（仅城市名）
    private List<String> filteredCityList; // 过滤后的列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.city_select);

        initViews();
        setupCityList();
        setupSearchFilter();
    }

    private void initViews() {
        etSearchCity = findViewById(R.id.search_city);
        rvCityList = findViewById(R.id.rv_city_list);
        rvCityList.setLayoutManager(new LinearLayoutManager(this));//设置垂直布局
    }

    private void setupCityList() {
        originalCityList = readCityDataFromFile();
        filteredCityList = new ArrayList<>(originalCityList);// 复制原始数据用于过滤

        CityAdapter adapter = new CityAdapter(filteredCityList);
        rvCityList.setAdapter(adapter);
    }

    private List<String> readCityDataFromFile() {
        List<String> cities = new ArrayList<>();
        try {
            InputStream inputStream = getResources().openRawResource(R.raw.city_data);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                String cityName = line.split(":")[0].trim(); // 提取城市名，忽略城市码
                cities.add(cityName);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cities;
    }

    private void setupSearchFilter() {
        etSearchCity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                filterCities(s.toString());//当搜索框文本变化时，调用 filterCities() 过滤城市列表。
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
    }

    private void filterCities(String query) {
        filteredCityList.clear();
        if (query.isEmpty()) {// 查询词为空时显示全部
            filteredCityList.addAll(originalCityList);
        } else {
            String lowerCaseQuery = query.toLowerCase();// 转小写匹配
            for (String city : originalCityList) {
                if (city.toLowerCase().contains(lowerCaseQuery)) {
                    filteredCityList.add(city);
                }
            }
        }
        ((CityAdapter) rvCityList.getAdapter()).notifyDataSetChanged();// 通知适配器数据变化，刷新列表
    }

    private class CityAdapter extends RecyclerView.Adapter<CityAdapter.ViewHolder> {
        private final List<String> cities;

        public CityAdapter(List<String> cities) {
            this.cities = cities;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    android.R.layout.simple_list_item_1, parent, false
            );
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            String city = cities.get(position);
            holder.textView.setText(city);

            holder.itemView.setOnClickListener(v -> {
                Intent intent = new Intent();
                intent.putExtra("city_name", city);
                setResult(Activity.RESULT_OK, intent);
                finish();
            });
        }//创建列表项的视图（View），并将其封装到 ViewHolder 中。

        @Override
        public int getItemCount() {
            return cities.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView textView;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                textView = itemView.findViewById(android.R.id.text1);
            }//ViewHolder 作用：缓存视图引用，避免重复调用 findViewById
        }
    }
//    初始化阶段：
//    RecyclerView 调用 getItemCount() 确定列表长度。
//    滑动时，调用 onCreateViewHolder() 创建新的 ViewHolder（当无复用 View 时）。
//    数据显示阶段：
//    RecyclerView 调用 onBindViewHolder()，将数据绑定到 ViewHolder 的视图。
//    视图滑动出屏幕后，ViewHolder 会被缓存，等待复用（提升性能）。
//    用户交互阶段：
//    点击列表项时，触发 itemView.setOnClickListener 中的逻辑，通过 Intent 返回数据。
}